import {
  BadRequestException,
  Body,
  Controller,
  Param,
  Post,
  Put,
  UploadedFile,
  UseGuards,
  UseInterceptors,
  UsePipes,
} from '@nestjs/common'
import { UserService } from './user.service'
import { FileInterceptor } from '@nestjs/platform-express'
import { User } from '../entities/user.entity'
import { uploadFile } from '../utils'
import { EncryptionPipe } from '../common/pipe/encryption.pipe'
import { AuthGuard } from '../common/guard/auth.guard'
import { ApiOperation, ApiTags } from '@nestjs/swagger'

@ApiTags('用户')
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  // 发送验证码
  @ApiOperation({ summary: '发送验证码' })
  @Post('sendCode')
  sendCode(@Body('phone') phone: string) {
    return this.userService.sendCode(phone)
  }

  // 注册
  @ApiOperation({ summary: '注册' })
  @Post('register')
  @UseInterceptors(FileInterceptor('avatar'))
  @UsePipes(EncryptionPipe)
  async register(@UploadedFile() file, @Body() body: User) {
    const user = await this.userService.findOne({ phone: body.phone })
    if (user) throw new BadRequestException('手机号已经注册了')
    body.avatar = uploadFile(file)
    return this.userService.register(body)
  }

  // 登录
  @ApiOperation({ summary: '登录' })
  @Post('login')
  @UsePipes(EncryptionPipe)
  login(@Body() body) {
    return this.userService.login(body)
  }

  // 修改
  @ApiOperation({ summary: '修改用户信息' })
  @Put(':id')
  @UseGuards(AuthGuard)
  @UseInterceptors(FileInterceptor('avatar'))
  edit(@UploadedFile() file, @Body() body: User, @Param('id') id) {
    if (file) {
      body.avatar = uploadFile(file)
    }
    return this.userService.edit(body, id)
  }
}
